﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
using ClassLibrary.Entity;
using System.Collections.Generic;
using ClassLibrary.SMTP;

/// <summary>
/// Summary description for EmailService
/// </summary>
public class EmailService
{
    private bool _IsAsyn = Convert.ToBoolean(Global.IS_ASYN);
    string EMAIL_PICKUP_FOLDER_LOCATION = Global.EMAIL_PICKUP_FOLDER_LOCATION;

    public EmailService()
    {
        try
        {
            _IsAsyn = Convert.ToBoolean(Global.IS_ASYN);
        }
        catch (Exception) { }
    }
    #region Private Methods

    private string CreateBodyNewsletter(string MailFilePath, string UnsubscribeLink)
    {
        try
        {
            if (File.Exists(MailFilePath))
            {
                string strResult = String.Empty;
                strResult = File.ReadAllText(MailFilePath);
                strResult = strResult.Replace("[UnsubscribeLink]", UnsubscribeLink);
                return strResult;
            }
            else throw new Exception("Email file not found");
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    private string CreateBodyMember(TblUserAccount member, string MailFilePath, string ActivationLink)
    {
        try
        {
            if (File.Exists(MailFilePath))
            {
                string strResult = String.Empty;
                strResult = File.ReadAllText(MailFilePath);
                strResult = strResult.Replace("[AccountName]", member.FirstName + " " + member.LastName);
                strResult = strResult.Replace("[AccountEmail]", member.Email);
                strResult = strResult.Replace("[ActivationLink]", ActivationLink);
                return strResult;
            }
            else throw new Exception("Email file not found");
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    private string CreateBodyOrder(TblUserAccount member, string MailFilePath, TblOrder Order, List<TblOrderDetail> OrderDetails)
    {
        string itemstr = string.Empty;
        string order_item = string.Empty;

        int STT = 0;

        try
        {
            if (File.Exists(MailFilePath))
            {
                string strResult = String.Empty;
                strResult = File.ReadAllText(MailFilePath);
                strResult = strResult.Replace("[AccountName]", member.FirstName + " " + member.LastName);
                strResult = strResult.Replace("[OrderId]", Order.OrderID.ToString());
                strResult = strResult.Replace("[OrderDate]", Convert.ToDateTime(Order.OrderDate).ToString());
                strResult = strResult.Replace("[DeliveryFee]", Order.DeliveryFee.ToString());
                strResult = strResult.Replace("[TotalAmount]", Order.Total.ToString("0,00.##"));

                foreach (TblOrderDetail orderdetail in OrderDetails)
                {
                    STT++;
                    itemstr += "<tr> <td> " + STT + "<td>" + orderdetail.Items.ItemName + "</td>" +
                        "<td align=\"right\">" + Convert.ToDouble(orderdetail.Price).ToString("0,00.##") + "</td>" +
                        "<td align=\"right\">" + orderdetail.Quantity.ToString() + "</td>" +
                        "<td align=\"right\">" + Convert.ToDouble(orderdetail.TotalAmount).ToString("0,00.##");
                }

                strResult = strResult.Replace("[OrderDetails]", itemstr);
                return strResult;
            }
            else throw new Exception("Email file not found");
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    private string CreateBodySalesOrder(TblUserAccount member, string MailFilePath, TblOrder Order, List<TblOrderDetail> OrderDetails)
    {
        string itemstr = string.Empty,
               order_item = string.Empty;
        int i = 0;
        try
        {
            if (File.Exists(MailFilePath))
            {
                string strResult = String.Empty;
                strResult = File.ReadAllText(MailFilePath);
                strResult = strResult.Replace("[AccountName]", member.FirstName + " " + member.LastName);
                strResult = strResult.Replace("[AccountEmail]", member.Email);
                strResult = strResult.Replace("[OrderId]", Order.OrderID.ToString());
                strResult = strResult.Replace("[OrderDate]", Convert.ToDateTime(Order.OrderDate).ToString());
                strResult = strResult.Replace("[DeliveryFee]", Order.DeliveryFee.ToString());
                strResult = strResult.Replace("[TotalAmount]", Order.Total.ToString("0,00.##"));

                foreach (TblOrderDetail entity in OrderDetails)
                {
                    i++;
                    itemstr += "<tr> <td> " + i + "<td>" + entity.Items.ItemName + "</td>" +
                        "<td align=\"right\">" + Convert.ToDouble(entity.Price).ToString("0,00.##") + "</td>" +
                        "<td align=\"right\">" + entity.Quantity.ToString() + "</td>" +
                        "<td align=\"right\">" + Convert.ToDouble(entity.TotalAmount).ToString("0,00.##");
                }

                strResult = strResult.Replace("[OrderDetails]", itemstr);
                return strResult;
            }
            else throw new Exception("Email file not found");
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    private string CreateBodyReceipt(string MemberName, string MailFilePath, string ReceiptNumber, string OrderId, string OrderDate, string OrderDetails, CheckoutContent checkoutContent)
    {
        try
        {
            if (File.Exists(MailFilePath))
            {
                string strResult = String.Empty;
                strResult = File.ReadAllText(MailFilePath);
                strResult = strResult.Replace("[AccountName]", MemberName);
                strResult = strResult.Replace("[ReceiptNumber]", ReceiptNumber);
                strResult = strResult.Replace("[OrderId]", OrderId);
                strResult = strResult.Replace("[OrderDate]", OrderDate);
                strResult = strResult.Replace("[OrderDetails]", OrderDetails);

                if (checkoutContent.Shipmentype == CheckoutContent.CheckoutType.Pickup)
                    strResult = strResult.Replace("[DeliveryMethod]", "Pickup at Cnet <b>Technology Braybrook Store</b><br />Address:5 Nguyen Van Sang ST, Tan Son Nhi Ward, Tan Phu Dist, Ho chi Minh City .<br />Trading hours: Mon - Saturday: 7:30AM - 5:00PM<br />Phone: (+84).862523486 ");
                //if (checkoutContent.Shipmentype == CheckoutContent.CheckoutType.Delivery)
                //    strResult = strResult.Replace("[DeliveryMethod]", "Delivery to:<br />" + checkoutContent.DeliveryStreet + "<br />" + checkoutContent.Suburb + " " + checkoutContent.PostCode);

              //  strResult = strResult.Replace("[DeliveryFee]", checkoutContent.DeliveryFee.ToString("c"));
                strResult = strResult.Replace("[HandlingFee]", checkoutContent.HandlingFee.ToString("0,00.##"));
                strResult = strResult.Replace("[TotalAmount]", checkoutContent.TotalAmount.ToString("0,00.##"));

                return strResult;
            }
            else throw new Exception("Email file not found");
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    private string CreateBodyChangePassword(string MemberName, string MailFilePath, string NewPassword)
    {
        try
        {
            if (File.Exists(MailFilePath))
            {
                string strResult = String.Empty;
                strResult = File.ReadAllText(MailFilePath);
                strResult = strResult.Replace("[AccountName]", MemberName);
                strResult = strResult.Replace("[NewPassword]", NewPassword);

                return strResult;
            }
            else throw new Exception("Email file not found");
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    private string CreateBodyContactUs(string MailFilePath, string CustomerName, string CustomerPhone, string CustomerEmail, string Message)
    {
        try
        {
            if (File.Exists(MailFilePath))
            {
                string strResult = String.Empty;
                strResult = File.ReadAllText(MailFilePath);
                strResult = strResult.Replace("[CustomerName]", CustomerName);
                strResult = strResult.Replace("[CustomerPhone]", CustomerPhone);
                strResult = strResult.Replace("[CustomerEmail]", "Customer Email: " + CustomerEmail);
                strResult = strResult.Replace("[Message]", Message);
                return strResult;
            }
            else throw new Exception("Email file not found");
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    #endregion

    public void SendWelcomeNewsletterEmail(string ReceiverEmailAddress, string EmailTemplateFilePath, string UnsubscribeLink)
    {
        try
        {
            MailProperties MailProp = new MailProperties();

            MailProp.SMTPHost = ConfigurationManager.AppSettings["SMTPServer"];

            MailProp.SMTPDisplayName = ConfigurationManager.AppSettings["SMTPName"].ToString();
            MailProp.SMTPFrom = ConfigurationManager.AppSettings["WebmasterEmail"];
            MailProp.SMTPSubject = "Welcome to ii-online Newsletter";

            MailProp.SMTPBody = CreateBodyNewsletter(EmailTemplateFilePath, UnsubscribeLink);
            MailProp.SMTPTo = ReceiverEmailAddress;
            MailProp.SMTPUsername = ConfigurationManager.AppSettings["SMTPUsername"];
            MailProp.SMTPPassword = ConfigurationManager.AppSettings["SMTPPassword"];
            MailProp.SMTPPort = Convert.ToInt32(ConfigurationManager.AppSettings["SMTPPort"]);

            MailProp.SendMail(_IsAsyn, Global.EMAIL_PICKUP_FOLDER_LOCATION);
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    public void SendWelcomeMembershipEmail(TblUserAccount member, string EmailTemplateFilePath, string ActivationLink)
    {
        try
        {
            MailProperties MailProp = new MailProperties();

            MailProp.SMTPHost = ConfigurationManager.AppSettings["SMTPServer"];
            MailProp.SMTPDisplayName = ConfigurationManager.AppSettings["SMTPName"].ToString();

            MailProp.SMTPFrom = ConfigurationManager.AppSettings["WebmasterEmail"].ToString();
            MailProp.SMTPSubject = "Welcome to ii-online";

            MailProp.SMTPBody = CreateBodyMember(member, EmailTemplateFilePath, ActivationLink);
            MailProp.SMTPTo = member.Email;
            MailProp.SMTPUsername = ConfigurationManager.AppSettings["SMTPUsername"];
            MailProp.SMTPPassword = ConfigurationManager.AppSettings["SMTPPassword"];
            MailProp.SMTPPort = Convert.ToInt32(ConfigurationManager.AppSettings["SMTPPort"]);

            MailProp.SendMail(_IsAsyn, Global.EMAIL_PICKUP_FOLDER_LOCATION);

        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    public void SendOrderEmail(TblUserAccount member, string EmailTemplateFilePath, TblOrder Order, List<TblOrderDetail> OrderDetails)
    {
        try
        {
            MailProperties MailProp = new MailProperties();

            MailProp.SMTPHost = ConfigurationManager.AppSettings["SMTPServer"];

            MailProp.SMTPDisplayName = ConfigurationManager.AppSettings["SMTPName"].ToString();
            MailProp.SMTPFrom = ConfigurationManager.AppSettings["ContactsEmail"].ToString();
            MailProp.SMTPSubject = "Order " + ConfigurationManager.AppSettings["SMTPName"].ToString();

            MailProp.SMTPBody = CreateBodyOrder(member, EmailTemplateFilePath, Order, OrderDetails);
            MailProp.SMTPTo = member.Email;
            MailProp.SMTPUsername = ConfigurationManager.AppSettings["SMTPUsername"];
            MailProp.SMTPPassword = ConfigurationManager.AppSettings["SMTPPassword"];
            MailProp.SMTPPort = Convert.ToInt32(ConfigurationManager.AppSettings["SMTPPort"]);

            MailProp.SendMail(_IsAsyn, Global.EMAIL_PICKUP_FOLDER_LOCATION);


        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    public void SendOrderEmailToSales(TblUserAccount member, string EmailTemplateFilePath, TblOrder Order, List<TblOrderDetail> OrderDetails)
    {
        try
        {
            MailProperties MailProp = new MailProperties();

            MailProp.SMTPHost = ConfigurationManager.AppSettings["SMTPServer"];

            MailProp.SMTPDisplayName = ConfigurationManager.AppSettings["SMTPName"].ToString();
            MailProp.SMTPFrom = Global.WEBMASTER_EMAIL_ADDRESS;
            MailProp.SMTPSubject = "Coming Order";

            MailProp.SMTPBody = CreateBodySalesOrder(member, EmailTemplateFilePath, Order, OrderDetails);
            MailProp.SMTPTo = Global.SALES_EMAIL_ADDRESS;
            MailProp.SMTPUsername = ConfigurationManager.AppSettings["SMTPUsername"];
            MailProp.SMTPPassword = ConfigurationManager.AppSettings["SMTPPassword"];
            MailProp.SMTPPort = Convert.ToInt32(ConfigurationManager.AppSettings["SMTPPort"]);

            MailProp.SendMail(_IsAsyn, Global.EMAIL_PICKUP_FOLDER_LOCATION);
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    public void SendChangePasswordEmail(TblUserAccount member, string EmailTemplateFilePath, string NewPassword)
    {
        try
        {
            MailProperties MailProp = new MailProperties();

            MailProp.SMTPHost = ConfigurationManager.AppSettings["SMTPServer"];

            MailProp.SMTPDisplayName = ConfigurationManager.AppSettings["SMTPName"].ToString();
            MailProp.SMTPFrom = ConfigurationManager.AppSettings["WebmasterEmail"].ToString();
            MailProp.SMTPSubject = "Password Changed";

            MailProp.SMTPBody = CreateBodyChangePassword(member.FirstName + " " + member.LastName, EmailTemplateFilePath, NewPassword);
            MailProp.SMTPTo = member.Email;
            MailProp.SMTPUsername = ConfigurationManager.AppSettings["SMTPUsername"];
            MailProp.SMTPPassword = ConfigurationManager.AppSettings["SMTPPassword"];
            MailProp.SMTPPort = Convert.ToInt32(ConfigurationManager.AppSettings["SMTPPort"]);

            MailProp.SendMail(_IsAsyn, Global.EMAIL_PICKUP_FOLDER_LOCATION);
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    public void SendContactUsEmail(string CustomerName, string CustomerPhone, string CustomerEmail, string ToEmail, string Subject, string Message, string EmailTemplateFilePath)
    {
        try
        {
            MailProperties MailProp = new MailProperties();

            MailProp.SMTPHost = ConfigurationManager.AppSettings["SMTPServer"];

            MailProp.SMTPDisplayName = "Customer Enquiry";
            string ENQUIRY_EMAIL_ADDRESS = ConfigurationManager.AppSettings["EnquiryEmail"].ToString();
            MailProp.SMTPFrom = ENQUIRY_EMAIL_ADDRESS;
            MailProp.SMTPSubject = Subject;

            MailProp.SMTPBody = CreateBodyContactUs(EmailTemplateFilePath, CustomerName, CustomerPhone, CustomerEmail, Message);
            MailProp.SMTPTo = ToEmail;

            MailProp.SMTPUsername = ConfigurationManager.AppSettings["SMTPUsername"];
            MailProp.SMTPPassword = ConfigurationManager.AppSettings["SMTPPassword"];
            MailProp.SMTPPort = Convert.ToInt32(ConfigurationManager.AppSettings["SMTPPort"]);

            MailProp.SendMail(_IsAsyn, Global.EMAIL_PICKUP_FOLDER_LOCATION);
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

}
